package com.rrd.hive.udf;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;


@Description(
        name = "geoip_to_city",
        value = "_FUNC_(ip) - Get city string from ip address",
        extended = "Example:\n> SELECT _FUNC_('39.155.171.170');\n  北京市"
)
public class GeoIpToCityUDF extends UDF {
    public static String dataFile = "/data/dim/geoip_to_city/GeoLite2-City.mmdb";
    public static DatabaseReader reader = null;
    static {
        try {
            readGeoLiteFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Configuration config() {
        System.setProperty("HADOOP_USER_NAME", "hdfs");
        Configuration conf = new Configuration();
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        return conf;
    }

    public static void readGeoLiteFile() throws IOException {
        Configuration conf = config();
        FileSystem fs = FileSystem.newInstance(URI.create(dataFile), conf);
        Path remotePath = new Path(dataFile);
        FSDataInputStream input = fs.open(remotePath);
        if (fs.exists(remotePath)) {
            reader = new DatabaseReader.Builder(input).build();
        } else {
            System.out.println("找不到指定的文件");
        }
    }

    public Text evaluate(String ip) {
        Text text = new Text("Null");
        try {
            if (ip == null || ip.equals("")) {
                return text;
            }

            String ipVal = ip.split(",")[0];
            InetAddress ipAddress = InetAddress.getByName(ipVal);

            CityResponse response = reader.city(ipAddress);
            String res = response.getMostSpecificSubdivision().getNames().get("zh-CN");
            res = (res == null ? "Null" : res);
            text.set(res);
        } catch (Exception e) {
            System.out.println("GeoIpToCityUDF excep: " + e.toString());
            e.printStackTrace();
        } finally {
            return text;
        }
    }
    public static void main(String[] args) throws Exception {
        GeoIpToCityUDF dfu = new GeoIpToCityUDF();
        System.out.println(dfu.evaluate("39.155.171.170"));
    }

}
